package cn.virens.app.main;

import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ComponentTimer<T> extends TimerTask {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	protected final AtomicInteger run = new AtomicInteger(0);

	protected final String name;
	protected final T cmpt;

	public ComponentTimer(T cmpt, String name) {
		this.cmpt = cmpt;
		this.name = name;
	}

	@Override
	public void run() {
		long s = System.currentTimeMillis();
		logger.debug("This {} thread run {} times.", name, run.incrementAndGet());

		try {
			doRun();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			long e = System.currentTimeMillis();
			logger.debug("This {} thread runs for {} milliseconds.", name, (e - s));
		}
	}

	protected abstract void doRun() throws Exception;

	@Override
	public String toString() {
		return "TimerTask [name=" + name + "]";
	}

}
